package com.leenleda.ips.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.leenleda.ips.BaseActivity;
import com.leenleda.ips.R;
import com.leenleda.ips.databinding.ActivityInsertBinding;
import com.leenleda.ips.activity.adapter.InsertAdapter;
import com.leenleda.ips.entity.InsertBean;
import com.leenleda.ips.receiver.Constant;
import com.leenleda.ips.util.GsonUtils;
import com.leenleda.ips.util.LogUtils;
import com.leenleda.ips.util.UShared;
import com.leenleda.ips.util.Utils;
import com.leenleda.ips.widget.banner.Banner;

import java.util.ArrayList;
import java.util.List;

public class InsertActivity extends BaseActivity implements Banner.OnListener {

    private ActivityInsertBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_insert);
//        binding = DataBindingUtil.setContentView(this, R.layout.activity_insert);

        setContentView( R.layout.activity_insert);
        binding = (ActivityInsertBinding) bindingView;

        String strData = getIntent().getStringExtra("strData");
        initData(strData);
    }

    @Override
    public void conTrollShow(int state, String... data) {
        switch (state){
            case Constant.PUSH_INSERT_MSG://显示滚动消息
                String msgData = data[0];
//                InsertBean insert = com.alibaba.fastjson.JSONObject.parseObject(msgData, InsertBean.class);
//                Log.e(tag, "==bundle===insert======" + insert);
                initData(msgData);
                break;
            case Constant.MISS_INSERT_MSG:
                long cur = Utils.getSetTime() / 1000;
                Log.e(tag, "=====miss=====" + duringTime + ",cur=" + cur );
                if (cur < duringTime)
                    return;
                finish();
//                missRollMsg(false);
                break;
            case Constant.SET_MEDIA_DATA:
                String type = data[0];
                switch (type){
                    case Constant.PUBLISH_SOURCE:
                        Utils.startActivity(this, new Intent(this, ImageActivity.class));
                        finish();
                        return;
                    case Constant.PUBLISH_WEB:
                        Utils.startActivity(this, new Intent(this, WebActivity.class));
                        finish();
                        return;
                    case Constant.PUBLISH_LIVE:
                        Utils.startActivity(this, new Intent(this, LiveActivity.class));
                        finish();
                        return;
                }
                break;
        }
    }

    private long duringTime = 0;
    private int scanTime = 0;
    private List<InsertBean.FileRecordsBean> dataList = new ArrayList<>();
    private List<InsertBean.FileRecordsBean> listPic = new ArrayList<>();
    private List<InsertBean.FileRecordsBean> videoList = new ArrayList<>();
    private InsertAdapter adapter;
    private String mVideoSource = "";
    private int resType = 100;
    private void initData(String strData){
        LogUtils.e("LSVSD", "=====strData==1===" + strData);

        LogUtils.e("LSVSD", "=====strData===3==" + strData);
        InsertBean insert = GsonUtils.getInstance().fromJson(strData, InsertBean.class);
//        InsertBean insert = JSONObject.parseObject(strData, InsertBean.class);
        resType = insert.getIntercutType();
        duringTime = Utils.getSetTime() / 1000 + insert.getIntercutTime();
        LogUtils.e(tag, "==EEEEEE==resType=======" +resType );
        switch (resType){ //插播类型100文字；200资源
            case 100:
                initSetting();
                binding.webView.setVisibility(View.VISIBLE);
                binding.webView.loadDataWithBaseURL(null, insert.getIntercutContent(), "text/html","UTF-8", null);
                return;
            case 200:
                binding.webView.setVisibility(View.GONE);
                break;
        }
        scanTime = insert.getResourceSwitchSpeed();
        dataList = insert.getFileRecords();
        for (int i = 0; i < dataList.size(); i ++){
            InsertBean.FileRecordsBean entity = dataList.get(i);
            entity.setPosition(i);
            if (entity.getFiletype() == 2)
                listPic.add(entity);
            else
                videoList.add(entity);
        }
        LogUtils.e(tag, "==EEEEEE==videoList=======" +videoList.size() );
        LogUtils.e(tag, "==EEEEEE==dataList=======" +dataList.size() );
        adapter = new InsertAdapter(this, listPic);
        binding.banner.setAdapter(adapter)
                .addBannerLifecycleObserver(this)//添加生命周期观察者
                .setLoopTime(scanTime * 1000)
                .setListener(this);
        controlShow(2);
    }

    private int curPos = -1;
    private void controlShow(int state){
        if (Utils.dKey("insert_control"))
            return;
        curPos ++;
        if (curPos > (dataList.size() - 1))
            curPos = 0;
        LogUtils.e(tag , "--************curPos*****22**********" + curPos + "(state:)" + state );
        LogUtils.e(tag , "--************curPos*****22*********3*" + dataList.get(curPos).getFiletype() + "(getPath:)" + dataList.get(curPos).getPath() );
        binding.str.setText(Utils.getStringValue(dataList.get(curPos).getPath()));
        if (dataList.get(curPos).getFiletype() == 2){
            binding.banner.start();
            binding.showVideo.setVisibility(View.GONE);
            if (listPic.size() == 1){
                new Handler().postDelayed(() -> controlShow(8), scanTime * 1000);
            }
        } else {
            LogUtils.e(tag , "--------------播放视频------------------" + curPos);
            binding.banner.stop();
            mVideoSource = dataList.get(curPos).getPath();
//            toPlayer(dataList.get(curPos));
            LogUtils.e(tag, "-showPlayer----mVideoSource--2----" + mVideoSource);
            binding.rlLoading.setVisibility(View.VISIBLE);
            binding.showVideo.setVisibility(View.VISIBLE);
            play();
        }
    }

    @Override
    public boolean scrollPosition(int position) {
        curPos = listPic.get(position).getPosition();
        binding.str.setText(Utils.getStringValue(listPic.get(position).getPath()));

        LogUtils.e(tag , "--************curPos*****11**********" + curPos + "==position==" + position);

        int upPos = position - 1;
        if (upPos < 0)
            upPos = listPic.size() - 1;
        int picUp = listPic.get(upPos).getPosition();
        int picThis = listPic.get(position).getPosition();
        LogUtils.e(tag , "==picUp==" + picUp + "===picThis==" + picThis + "==size==" + dataList.size() );

        if (listPic.size() == dataList.size())//当所有资源为图片时保持一直滚动
            return false;

        if (position == 0 && picUp != dataList.size() - 1){//当上一个不是所有dataList的最后一个时
            LogUtils.e(tag , "------picUp---------" + picUp );
            curPos = picUp;
            controlShow(3);
            return true;
        }

        int posFrom = picThis - picUp;
        if (picThis < picUp) {
            posFrom = picThis;
            curPos = -1;
        }

        if(posFrom > 1){
            if (curPos != -1)
                curPos = picUp;
            controlShow(4);
            return true;
        }
        return false;
    }

    private void play(){
        LogUtils.e(tag, "-showPlayer----state----1--" + state);
        switch (state) {
            case 0:
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                initMediaPlayer();
                state = 4;
                seedTo();
                binding.videoview.start();
                binding.rlLoading.setVisibility(View.GONE);
                break;
            case 4:
                state = 0;
                binding.videoview.pause();
                play();
                break;
            case 5:
                state = 4;
                seedTo();
                binding.videoview.start();
                binding.rlLoading.setVisibility(View.GONE);
                break;
            case 9:
                binding.videoview.setVideoPath(mVideoSource);
                seedTo();
                binding.videoview.start();
                binding.rlLoading.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 记录播放位置
     */
    private int mLastPos = 0;

    private void seedTo(){
        if (mLastPos > 0) {
            binding.videoview.seekTo(mLastPos);
            mLastPos = 0;
        }
    }

    /**
     * 状态：0，初始状态，3，播放器初始化完成(prepared)，4，播放中，
     * 5， 暂停中，8，播放完毕，9，播放错误
     */
    int state = 0;
    private void initMediaPlayer() {
        binding.videoview.setVideoPath(mVideoSource);
        binding.videoview.setOnCompletionListener(mp -> {
            state = 0;
            controlShow(6);
        });
        binding.videoview.setOnErrorListener((mp, what, extra) -> {
            LogUtils.e("LSNVLSDV", "===extra======" + extra);
            LogUtils.e("LSNVLSDV", "===what======" + what);
            mp.stop();
            state = 0;
            controlShow(8);
            return true;
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.e("FDSFS","---onResume---: " + resType);
        if (resType == 200)
            controlShow(7);
        String per = Utils.getStringValue(UShared.getString(Constant.DEVICE_PERMISSION_STATE));
        if (per.isEmpty())
            binding.tips.setVisibility(View.GONE);
        else {
            binding.tips.setText(per);
            binding.tips.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.e("FDSFS","---onPause---: ");
        binding.videoview.pause();
//        binding.videoview.suspend();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.e("FDSFS","---onDestroy---: ");
        binding.webView.clearHistory();
        binding.webRoot.removeView(binding.webView);
        binding.webView.destroy();
    }

    private void initSetting(){
        LogUtils.e("retrofitBack", "====================");
        WebSettings webSettings = binding.webView.getSettings();
        webSettings.setJavaScriptEnabled(true);//设置WebView属性，能够执行Javascript脚本
        webSettings.setAllowFileAccess(true);//设置可以访问文件
        webSettings.setBuiltInZoomControls(false); //设置支持缩放
        webSettings.setDisplayZoomControls(false);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            binding.webView.getSettings().setMixedContentMode(binding.webView.getSettings()
                    .MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }
        binding.webView.setWebViewClient(new MyWebViewClient());//富文本
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            imgReset();//重置webview中img标签的图片大小
            // html加载完成之后，添加监听图片的点击js函数
//            addImageClickListner();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    private void imgReset() {
        binding.webView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "var img = objs[i];   " +
                "    img.style.maxWidth = '100%'; img.style.height = 'auto';  " +
                "}" +
                "})()");
    }
}